#include "user.h"

bool user_init(user_ptr *ul){
	*ul = (user_ptr)malloc(sizeof(user));
	if((*ul) != NULL){
		//匿名用户
		(*ul)->next = NULL;
		strcpy((*ul)->uname, "anonymous");
		strcpy((*ul)->passwd, "@");
		strcpy((*ul)->priv, "ls,cd,pwd,get");

		return true;
	}

	return false;
}

void user_push(user_ptr ul, user_ptr user_n){
	user_ptr temp = (user_ptr)malloc(sizeof(user));

	strcpy(temp->uname, user_n->uname);
	strcpy(temp->passwd, user_n->passwd);
	strcpy(temp->priv, user_n->priv);

	temp->next = ul->next;
	ul->next = temp;
}

bool user_parser(user_ptr ul, FILE *fp){
	user user_n;
	char buf[USER_LINE_LEN];
	char *p;

	while((fgets(buf, sizeof(buf), fp)) != NULL){
		int len = strlen(buf);
		if(buf[len-1] == 10){
			buf[len-1] = 0;
		}
		if(buf[0] == '#' || !isalpha(buf[0]))
			continue;
		p=strtok(buf, ":");
		//用户名
		if(p == NULL)
			continue;
		strcpy(user_n.uname, p);
		//密码
		if((p=strtok(NULL, ":")) == NULL)
			continue;
		strcpy(user_n.passwd, p);
		//权限
		if((p=strtok(NULL, ":")) == NULL)
			continue;
		strcpy(user_n.priv, p);
		user_push(ul, &user_n);
	}

	if(user_size(ul) == 0)
		return false;
	return true;
}

int user_size(user_ptr ul){
	user_ptr p = ul->next;
	register int len=0;

	while(p != NULL){
		len++;
		p = p->next;
	}

	return len;
}

void user_destroy(user_ptr *ul){
	user_ptr p=*ul,q=p->next;

	while(q != NULL){
		p->next = q->next;
		free(q);
		q = p->next;
	}

	free(*ul);
	*ul = NULL;
}

void user_traverse(user_ptr ul, void (*func)(user_ptr)){
	user_ptr p = ul->next;

	while(p != NULL){
		func(p);
		p = p->next;
	}
}

user_ptr user_auth(user_ptr ul, char *uname, char *passwd){
	user_ptr p=ul;

	while(p != NULL){
		if(!strcmp("anonymous", uname)){//匿名用户
			return p;
		}
		if(!strcmp(p->uname, uname)){
			if(!strcmp(p->passwd, passwd)){
				return p;
			}
		}
		p = p->next;
	}

	return NULL;
}

void print_u(user_ptr user_p){
	printf("uname: %s\npasswd: %s\npriv: %s\n", user_p->uname,
			user_p->passwd, user_p->priv);
	fputc('\n', stdout);
}
